﻿using System;
using System.Configuration;
using System.Globalization;
using System.IO;
using System.Text;
using System.Threading;
using System.Xml;
using System.Reflection;
using YEA.Infrastructure.Gateway;
using YEA.Utilities;
using YEA.Utilities.Logging;
using YEA.Utilities.Notifications;
using YEA.Utilities.Common;

namespace HelloWorld_SampleApp
{
    class Program
    {
        private static ExceptionManager em;
        private static ILog logger;
        private static INotify notifier;

        private static void Initialize()
        {
            try
            {
                logger = new Logger("logPublisher");
                notifier = new Notifier("notificationPublisher");
                em = new ExceptionManager(logger, notifier);
            }
            catch (Exception ex)
            {
                Console.WriteLine(string.Format("Program {0} failed to initialize, exception thrown:", UtilitiesHelper.GetMyProgramFullName()));
            }
        }
        
        static void Main(string[] args)
        {
            Initialize();
            var counter = 0;
            try
            {
                using (var gf = new GatewayFactory())
                {
                    var mc = new MyConverter();
                    var publisher = gf.GetPublisher("orderPublisher", mc.ConvertObjectToMessage);
                    while (!Console.KeyAvailable)
                    {
                        try
                        {
                            publisher.Publish("Hello world");

                            logger.Write(string.Format("published message {0}", counter++), LogType.Information);
                            Thread.Sleep(1000);
                            throw new FakeException("testing exception management");
                        }
                        catch (FakeException ex)
                        {
                            em.ManageException(ex, LogType.Error);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                em.ManageException(ex, LogType.Fatal);
            }
        }

       
    }
    class MyConverter : YEA.Infrastructure.Gateway.Converter.StringToMessageConverter
    {
        public override Message ConvertObjectToMessage(RabbitMQ.Client.IModel channel, object packetToSend)
        {
            var message = base.ConvertObjectToMessage(channel, packetToSend);
            message.RoutingKey = System.Reflection.Assembly.GetCallingAssembly().FullName;
            return message;
        }
    }
}
